package com.learning.springmvc.advance.data.bind.converter.convert;

import com.google.common.base.Splitter;
import com.learning.springmvc.advance.data.bind.converter.bean.User;
import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * ClassName: StringToUserC
 * Description: 请求参数的字符串转换User对象
 * <p>
 * 字符串格式：<name>:<mobile>:<birthday>
 * <p>
 * Date: 2019/5/21 16:07 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class StringToUserConverter implements Converter<String, User> {
    private final SimpleDateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public User convert(String source) {

        // 将格式为 <name>:<mobile>:<birthday> 的字符串转换为User对象
        List<String> list = Splitter.on(":").splitToList(source);

        User user = new User();
        user.setName(list.get(0));
        user.setMobile(list.get(1));

        try {
            user.setBirthday(FORMAT.parse(list.get(2)));
        } catch (ParseException e) {
        }
        return user;
    }
}
